<template>
  <div>
    <div class="app-container">
      <el-form
        :model="queryParams"
        ref="queryRef"
        v-show="showSearch"
        :inline="true"
      >
        <el-form-item label="回收编码" prop="recycleCode">
          <el-input
            v-model="queryParams.recycleCode"
            placeholder="请输入回收编码"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="商品类目" prop="category">
          <el-select
            v-model="queryParams.category"
            filterable
            clearable
            multiple
            collapse-tags
            collapse-tags-tooltip
            placeholder="请选择商品类目"
            style="width: 220px"
          >
            <el-option
              v-for="item in goods_category"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品品牌" prop="brand">
          <el-select
            v-model="queryParams.brand"
            filterable
            reserve-keyword
            clearable
            style="width: 230px"
            allow-create
            default-first-option
            placeholder="请选择品牌"
          >
            <el-option
              v-for="item in item_brand"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="商品编码" prop="ref">
          <el-input
            v-model="queryParams.ref"
            placeholder="请输入商品编码"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="商品型号" prop="model">
          <el-input
            v-model="queryParams.model"
            placeholder="请输入商品型号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="商品状态" prop="itemStatus">
          <el-select
            v-model="queryParams.itemStatus"
            placeholder="状态"
            style="width: 90px"
            clearable
          >
            <el-option
              v-for="i in item_status"
              :key="i.value"
              :label="i.label"
              :value="i.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="回收价格" prop="recyclePrice">
          <el-input
            v-model="queryParams.recyclePrice"
            placeholder="请输入"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="打款时间">
          <el-date-picker
            v-model="RecycleTime"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            style="width: 230px"
            end-placeholder="结束日期"
            :shortcuts="shortcuts"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['erp:skesItem:add']"
            >回收号登记</el-button
          >
        </el-col>

        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            @click="handleDelete"
            :disabled="!selectionData.length"
            v-hasPermi="['erp:skesItem:remove']"
            >删除</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="Upload"
            @click="handleImport"
            v-hasPermi="['erp:skesItem:import']"
            >导入</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['erp:skesItem:export']"
            >导出</el-button
          >
        </el-col>
        <right-toolbar
          v-model:showSearch="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>
      <el-table
        v-loading="loading"
        height="65vh"
        :data="dataList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="回收编码" prop="recycleCode" align="center" />
        <el-table-column label="商品编码" prop="ref" align="center" />
        <el-table-column
          label="商品型号"
          prop="model"
          width="120"
          align="center"
        />
        <el-table-column label="快递单号" prop="expressNo" align="center" />
        <el-table-column label="回收价格" prop="recyclePrice" align="center" />
        <el-table-column label="品牌" prop="brand" align="center">
          <template #default="scope">
            <dict-tag
              v-if="scope.row.brand"
              :options="item_brand"
              :value="scope.row.brand"
            />
            <span v-else>{{ scope.row.brandName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="商品正面图"
          prop="watchImageUrl"
          align="center"
          width="110"
        >
          <template #default="scope">
            <div style="display: flex; align-items: center; width: 50px">
              <el-image
                :src="scope.row.watchImageUrl"
                :preview-src-list="[scope.row.watchImageUrl]"
                preview-teleported
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="商品背面图"
          prop="watchImageUrlBack"
          align="center"
          width="110"
        >
          <template #default="scope">
            <div style="display: flex; align-items: center; width: 50px">
              <el-image
                :src="scope.row.watchImageUrlBack"
                :preview-src-list="[scope.row.watchImageUrlBack]"
                preview-teleported
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="二维码"
          prop="imgUrl"
          align="center"
          width="150"
        >
          <template #default="scope">
            <div style="display: flex; align-items: center; width: 120px">
              <el-image
                :src="scope.row.imgUrl"
                :preview-src-list="[scope.row.imgUrl]"
                preview-teleported
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="商品类目" prop="category" align="center">
          <template #default="scope">
            <dict-tag :options="goods_category" :value="scope.row.category" />
          </template>
        </el-table-column>
        <el-table-column
          label="打款时间"
          prop="paymentTime"
          align="center"
          width="100"
        />
        <el-table-column label="打款状态" prop="paymentStatus" align="center">
          <template #default="scope">
            <dict-tag
              :options="payment_status"
              :value="scope.row.paymentStatus"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="回收人用户名"
          prop="recyclePersonName"
          width="130"
          align="center"
        />
        <el-table-column
          label="回收人昵称"
          prop="recyclePerson"
          align="center"
          width="100"
        />
        <el-table-column
          label="回收客户"
          prop="recycleCustomer"
          align="center"
        />
        <el-table-column
          label="商品退货状态"
          prop="goodsStatus"
          align="center"
          width="130"
        >
          <template #default="scope">
            <dict-tag :options="goods_status" :value="scope.row.goodsStatus" />
          </template>
        </el-table-column>
        <el-table-column
          label="备注"
          prop="remark"
          align="center"
          width="200"
        />
        <el-table-column
          label="操作"
          align="center"
          width="80"
          fixed="right"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <!-- <el-tooltip content="图片上传" placement="top">
              <el-button
                link
                type="primary"
                icon="Upload"
                @click="handleUpload(scope.row.id)"
              ></el-button>
            </el-tooltip> -->
            <el-tooltip content="修改" placement="top">
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['erp:skesItem:edit']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['erp:skesItem:remove']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div class="footer-msg">
        <p>
          <i class="el-icon-warning blue-text"></i>
          数量总和:
          <span class="blue-text">{{ summaryInfo.sumCount || "N/A" }}</span>
        </p>
        <p>
          成本金额:<span class="blue-text">{{
            summaryInfo.sumAmount || "N/A"
          }}</span>
        </p>
      </div>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <add
      v-model:visible="addParams.visible"
      :params="addParams"
      @refresh="getList"
    />
    <!-- 导入对话框 -->
    <el-dialog
      :title="upload.title"
      v-model="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
              >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 上传图片 -->
    <el-dialog
      title="图片上传"
      v-model="uploadImage"
      width="400px"
      append-to-body
      :before-close="clearImg"
    >
      <el-upload
        v-model:file-list="fileList"
        ref="uploadRef"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :limit="1"
        :on-exceed="handleExceed"
        accept=".jpg,.png,.jpeg"
        :auto-upload="false"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitUpload">确 定</el-button>
          <el-button @click="clearImg">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="SkesItem">
import {
  listTable,
  delItem,
  uploadApi,
  optionSelect,
} from "@/api/system/skesItem";
import { getToken } from "@/utils/auth";
import { genFileId } from "element-plus";
import Add from "./add.vue";
const { proxy } = getCurrentInstance();
const dataList = ref([]);
const selectionData = ref([]);
const total = ref(0);
const loading = ref(true);
const showSearch = ref(true);
const summaryInfo = ref({});
const { item_brand } = proxy.useDict("item_brand");
const { item_status } = proxy.useDict("item_status");
const { goods_category, goods_status, payment_status } = proxy.useDict(
  "goods_category",
  "goods_status",
  "payment_status"
);
Date.prototype.format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1, // 月份
    "d+": this.getDate(), // 日
    "h+": this.getHours(), // 小时
    "m+": this.getMinutes(), // 分
    "s+": this.getSeconds(), // 秒
    "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
    S: this.getMilliseconds(), // 毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (this.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
    }
  }
  return fmt;
};
const businessDate = ref([
  new Date(new Date().getTime() - 3600 * 1000 * 24 * 30).format("yyyy-MM-dd"),
  new Date().format("yyyy-MM-dd"),
]);
const shortcuts = [
  {
    text: "最近一周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "最近一个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: "最近三个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];
const addParams = ref({
  type: "add",
  visible: false,
  id: undefined,
});

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    brand: undefined,
    createBy: undefined,
    model: undefined,
    recyclePrice: undefined,
    ref: undefined,
    remark: undefined,
    category: undefined,
    itemStatus: undefined,
    recycleCode: undefined,
  },
});
const { queryParams, form, rules } = toRefs(data);
/*** 导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,

  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/system/skesItem/importData",
});
/** 查询列表 */
function getList() {
  loading.value = true;
  listTable(
    proxy.addDateRange(queryParams.value, RecycleTime.value, "RecycleTime")
  ).then((response) => {
    dataList.value = response.rows;
    summaryInfo.value = { ...response, rows: undefined };
    total.value = response.total;
    loading.value = false;
  });
}

/** 图片上传 */
const itemId = ref();
const fileList = ref([]);
const uploadImage = ref(false);
const uploadRef = ref();
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
function handleUpload(id) {
  itemId.value = id;
  uploadImage.value = true;
}
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url;
  dialogVisible.value = true;
};
const handleExceed = (files) => {
  uploadRef.value.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  uploadRef.value.handleStart(file);
};
function clearImg() {
  itemId.value = undefined;
  fileList.value = [];
  uploadImage.value = false;
}
async function submitUpload() {
  await uploadApi({
    itemId: itemId.value,
    file: fileList.value[0].raw,
  });
  proxy.$modal.msgSuccess("上传商品图片成功");
  getList();
  clearImg();
}
/** 商品下拉框 */
const remoteLoading = ref(false);
const itemOptions = ref([]);
async function getItemOption(query) {
  if (query) {
    remoteLoading.value = true;
    const { data } = await optionSelect({ queryKey: query });
    itemOptions.value = data.map((i) => {
      const { id, brand, ref: re, recyclePrice, model, expressNo } = i;
      return {
        value: id,
        brand,
        label: `${id},${brand},${re},${recyclePrice},${model},${
          expressNo || ""
        }`,
      };
    });
    remoteLoading.value = false;
  }
}
function handleChooseItem(id) {
  const { brand } = itemOptions.value.find((i) => i.value === id);
  queryParams.value.brand = brand;
}
getItemOption(" ");
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}
const RecycleTime = ref([]);
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.brand = undefined;
  RecycleTime.value = [];
  handleQuery();
}
/** 导入按钮操作 */
function handleImport() {
  upload.title = "用户导入";
  upload.open = true;
}
/** 下载模板操作 */
function importTemplate() {
  proxy.download(
    "system/skesItem/importTemplate",
    {},
    `skesItem_template_${new Date().getTime()}.xlsx`
  );
}
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
      response.msg +
      "</div>",
    "导入结果",
    { dangerouslyUseHTMLString: true }
  );
  getList();
};
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}
/** 导出按钮操作 */
function handleExport() {
  const [beginRecycleTime, endRecycleTime] = RecycleTime.value;
  proxy.download(
    "system/skesItem/export",
    {
      ...queryParams.value,
      params: { beginRecycleTime, endRecycleTime },
    },
    `goods_${new Date().getTime()}.xlsx`
  );
}
/** 删除按钮操作 */
function handleDelete(row) {
  let ids = [],
    refs = [];
  if (row.id) {
    ids = row.id;
    refs = row.ref;
  } else {
    selectionData.value.forEach((i) => {
      ids.push(i.id);
      refs.push(i.ref);
    });
    ids = ids.join(",");
    refs = refs.join(",");
  }
  proxy.$modal
    .confirm('是否确认删除商品编码为"' + refs + '"的数据项?')
    .then(function () {
      return delItem(ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
/** 添加商品*/
function handleAdd() {
  addParams.value = {
    id: undefined,
    type: "add",
    visible: true,
  };
}
/** 修改商品*/
function handleUpdate(row) {
  addParams.value = {
    type: "edit",
    visible: true,
    id: row.id,
  };
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  selectionData.value = selection.map((i) => ({
    id: i.id,
    ref: i.ref,
  }));
}
getList();
</script>
